package org.simpleframwork.util;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileFilter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

@Slf4j
public class ClassUtil {

    public static final String FILE_PROTOCOL = "file";

    /**
     * 获取包下类的集合
     * @author weiyuewen 2020/6/10 15:20
     */
    public static Set<Class<?>> extractPackageClass(String packageName) {
        //1 获取类加载器
        ClassLoader classLoader = getClassLoader();
        //2 通过类加载器获取到加载的资源
        URL url = classLoader.getResource(packageName.replace(".", "/"));
        if (url == null){
            log.warn("unable to retrieve anything from package:"+ packageName);
            return null;
        }
        //3 依据不同的资源类型，采用不同的方式获取资源的集合
        Set<Class<?>> classSet = null;
        //过滤出文件类型的资源
        if (url.getProtocol().equalsIgnoreCase(FILE_PROTOCOL)){
            classSet = new HashSet<>();
            File packageDirectory = new File(url.getPath());
            extractClassFile(classSet, packageDirectory, packageName);
        }
        return classSet;
    }

    /**
     * 递归获取目标目录下所有的class文件
     * @author weiyuewen 2020/6/10 15:40
     */
    private static void extractClassFile(Set<Class<?>> emptyClassSet, File fileSource, String packageName) {
        if (!fileSource.isDirectory()){
            return;
        }
        //如果是文件夹，列出当前文件下的所有文件和文件夹
        File[] files = fileSource.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                if (file.isDirectory()){
                    return true;
                } else {
                    //获取文件的绝对值路径
                    String absoluteFilePath = file.getAbsolutePath();
                    if (absoluteFilePath.endsWith(".class")){
                        //如果是class文件，直接加载
                        addToClassSet(absoluteFilePath);
                    }
                }
                return false;
            }
            private void addToClassSet(String absoluteFilePath) {
                //从class文件的绝对值路径中提取出包含了package的类名
                absoluteFilePath = absoluteFilePath.replace(File.separator, ".");
                String className = absoluteFilePath.substring(absoluteFilePath.indexOf(packageName));
                className = className.substring(0, className.lastIndexOf("."));
                //通过反射机制获取对应的class，加载到classSet
                Class targetClass = loadClass(className);
                emptyClassSet.add(targetClass);
            }
        });

        if (files != null){
            for (File f:files){
                extractClassFile(emptyClassSet, f, packageName);
            }
        }
    }

    /**
     * 获取class对象
     * @author weiyuewen 2020/6/10 15:54
     */
    public static Class<?> loadClass(String className){
        try {
            return Class.forName(className);
        } catch (ClassNotFoundException e) {
            log.error("no class error", e);
            throw new RuntimeException(e);
        }
    }


    public static ClassLoader getClassLoader(){
        return Thread.currentThread().getContextClassLoader();
    }

    /**
     * 实例化class
     * @author weiyuewen 2020/6/10 17:29
     */
    public static <T> T newInstance(Class<?> clazz, boolean accessible){
        try {
            Constructor constructor = clazz.getDeclaredConstructor();
            constructor.setAccessible(accessible);
            return  (T)constructor.newInstance();
        } catch (Exception e) {
            log.error("new Instance error", e);
            throw new RuntimeException(e);
        }
    }


    /**
     * 设置类的属性值
     * @author weiyuewen 2020/6/12 14:29
     */
    public static void setField(Field field, Object target, Object value, boolean accessible){
        field.setAccessible(accessible);
        try {
            field.set(target,value);
        } catch (IllegalAccessException e) {
            log.error("set field error", e);
            throw new RuntimeException(e);
        }
    }





}
